from web import template

UNITS = ("b", "Kb", "Mb", "Gb", "Tb")
PRIORITIES = ("off", "low", "normal", "high")
STATUS_IMAGES = ("<img src='/static/images/mini/media-record.png'>",
                "<img src='/static/images/mini/go-down.png'>",
                "<img src='/static/images/mini/go-up.png'>")
STATUS = ("Stop", "Download", "Upload")

def human_size(bytes):
    bytes = abs(bytes)
    i = 0
    while bytes>1024:
        bytes = bytes/1024.0
        i+=1
    return "%2.1f%s" % (bytes, UNITS[i])
template.Template.globals['human_size'] = human_size
    
def priority_str(n, d = None):
    if not d is None:
        n+=1
    return PRIORITIES[n]
template.Template.globals['priority_str'] = priority_str
    
def status_replace(n):
    return STATUS_IMAGES[n]
template.Template.globals['status_replace'] = status_replace
    
def ratio(n):
    ratio = int(n)/1000.0
    return "%2.2f%%" % ratio
template.Template.globals['ratio'] = ratio
    
def leechers(a, c):
    return (a-c)
template.Template.globals['leechers'] = leechers
    
def processbar(d, a):
    d = abs(d)
    a = abs(a)
    if a==0: a = 100
    p = d/(a/100.0)
    p = abs(p)
    if p>100: p = 100
    return "<div class='percent'>%d%%</div><div class='processbar'><div style='width:%dpx'></div></div>" % (p, p/2)
template.Template.globals['processbar'] = processbar

def status_str(n):
    return STATUS[n]
template.Template.globals['status_str'] = status_str

def priority_select(n, d = None):
    a = 4
    i = 0
    if not d is None:
        n+=1
        i+=1
    result = ""
    while i<a:
        if i==n:
            result+="<option value=%d%s>%s</option>" % (i, " selected", PRIORITIES[i])
        else:
            result+="<option value=%d%s>%s</option>" % (i, "", PRIORITIES[i])
        i+=1
    return result
template.Template.globals['priority_select'] = priority_select

def space(n):
    n-=1
    if n<0: n = 0
    return "|-"+"-"*n
template.Template.globals['space'] = space
